﻿using SciChart.Charting.ViewportManagers;
using SciChart.Charting.Visuals.Axes;
using SciChart.Charting.Visuals;
using SciChart.Data.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace AconITF.Extension
{
	public class ViewPortSciChart : DefaultViewportManager
	{
		public ViewPortSciChart()
		{

		}

		public int ItemCount { get; set; }

		public bool IsRealTime { get; set; }
		public ViewPortSciChart(int count)
		{
			ItemCount = count;
		}

		SciChartSurface sciChartSurface;
		public override void AttachSciChartSurface(ISciChartSurface scs)
		{
			base.AttachSciChartSurface(scs);
			sciChartSurface = scs as SciChartSurface;
			sciChartSurface.MouseDoubleClick += SciChartSurface_MouseDoubleClick;
		}

		public ISciChartSurface ParentSurface { get; private set; }
		protected override IRange OnCalculateNewXRange(IAxis xAxis)
		{
			if (!(xAxis.DataRange is DoubleRange rangeMax))
			{
				return new DoubleRange();
			}
			if (sciChartSurface.ZoomState == ZoomStates.UserZooming)
			{
				return xAxis.VisibleRange;
			}

			return new DoubleRange((rangeMax.Max - ItemCount) > 0 ? (rangeMax.Max - ItemCount) : 0,
			(rangeMax.Max < ItemCount ? ItemCount + 0 : rangeMax.Max + 0));
		}

		private void SciChartSurface_MouseDoubleClick(object sender, MouseButtonEventArgs e)
		{
			if (IsRealTime)
			{
				return;
			}
			if (e.ChangedButton == MouseButton.Right)
			{
				sciChartSurface.ZoomState = ZoomStates.AtExtents;
			}

			else if (e.ChangedButton == MouseButton.Left)
			{
				sciChartSurface.ZoomState = ZoomStates.UserZooming;
				sciChartSurface.ZoomExtentsX();
				sciChartSurface.ZoomExtentsY();
			}
		}
	}
}
